import axios from 'axios'
import Router from '@/router/index';
import {getToken, setToken, removeToken }from '@/libs/cache'
import loading from '@/libs/loading'
import permission from '@/libs/permission'
import {Notify }from 'quasar'

if (process.env.MOCK) {
  require('@/mockjs')
}

// create an axios instance
const service = axios.create( {
  //baseURL: process.env.SERVER_API,
  timeout:20000 // request timeout
})

// request interceptor
service.interceptors.request.use(config =>  {
  // Do something before request is sent
  // if ( ! permission.check(config)) {
  //   Notify.create( {
  //     message:"没有请求权限"
  //   })
  //   throw "403"
  // }
  // loading.show(config)
  let token = getToken();
  if (token) {
    //config.headers['X-Requested-With'] = 'XMLHttpRequest'
    config.headers['Access-Control-Allow-Origin'] = '*'
    config.headers['X-Auth-Token'] = token
  }
  config.url = '/api' + config.url;
  return config
}, error =>  {
  Promise.reject(error)
})

service.interceptors.response.use(
  response =>  {
    // loading.hide(response.config)
    const res = response.data;
    return response.data;
    // }
  },
  error =>  {
    loading.hide(error.config)
    let isToLogin = false;
    if (error.response && error.response.status === 403) {
      removeToken();
      isToLogin = true;
        Router.push( {
          name:"login"
        });
      return false;
    }else if (error.response && error.response.status === 500) {
      this.$q.notify( {
        message:this.$q.i18n.xw.notify.err_system,
        position:'bottom-right'
      })
    }else {
      Notify.create( {
        message:$q.i18n.xw.notify.err_network,
        position:'bottom-right'
      })
    }
    return Promise.reject(error)
  });
export default service



